<template>
  <div @click="closeTag">
    <t-tag v-for="tag in dynamicTagList" type="primary" :data-tagId="tag.id" closable>{{
        tag.text
      }}
    </t-tag>

    <t-input class="ml-2" placeholder="新增一个标签" ref="inputTag" @keypress.enter="addNewTag"></t-input>
  </div>
</template>

<script lang="ts">
import {ref} from 'vue'

export default {
  setup() {
    const inputTag = ref(null)
    let count = 3
    const dynamicTagList = ref([
      {text: '标签1', id: '1'},
      {text: '标签2', id: '2'}
    ])

    const closeTag = ($event: MouseEvent) => {
      let target = $event.target as HTMLElement
      while (target) {
        if (target.dataset.hasOwnProperty('tagid')) {
          const id = target.dataset['tagid']
          dynamicTagList.value = dynamicTagList.value.filter(tag => tag.id !== id)
          return
        }
        target = target.parentElement
      }
    }

    const addNewTag = ($event: KeyboardEvent) => {
      const target = $event.target as HTMLInputElement
      const text = target.value
      dynamicTagList.value.push({text, id: (count++).toString()})

      target.value = ''
      inputTag.value.inputValue = ''
    }


    return {
      dynamicTagList,
      closeTag,

      addNewTag,
      inputTag
    }
  }
}
</script>
